package com.yun.util.yun.utils.file;

import com.yun.util.UnicodeReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.Charset;
import java.util.UUID;

/**
 * @DESC: 文件字编码格式转换工具
 */

public class FileUtil {
    private static Logger logger = LoggerFactory.getLogger(FileUtil.class);

    public FileUtil() {
    }
    

    public static InputStream encodeFormatTransfer(MultipartFile multfile) throws IOException {
            // 获取文件名
            String fileName = multfile.getOriginalFilename();
            // 获取文件后缀
            String prefix=fileName.substring(fileName.lastIndexOf("."));
            // 用uuid作为文件名，防止生成的临时文件重复
            final File tempFile = File.createTempFile(UUID.randomUUID().toString(), prefix);
            // MultipartFile to File
            multfile.transferTo(tempFile);
            //业务逻辑
            String oldCode = guessEncoding(tempFile);
            if(logger.isInfoEnabled()){
                logger.info("文件的编码格式为：" + oldCode);
            }
            if (oldCode!=null) {
                if (!oldCode.equalsIgnoreCase("utf-8")) {
                    write(tempFile, "utf-8", readOther(tempFile, oldCode));
                    logger.info("-------非utf-8格式的进行转换-------");
                } else {
                    write(tempFile, "utf-8", readUtf(tempFile, oldCode));
                    logger.info("-------utf-8格式的进行转换(处理有无BOM)-------");
                }
            }
            String newCode = guessEncoding(tempFile);
            if(logger.isInfoEnabled()){
                logger.info("转换后文件的编码格式为：" + newCode);
            }
            InputStream in=new FileInputStream(tempFile);
            //程序结束时，删除临时文件
        if (tempFile.exists()) {
            tempFile.delete();
        }
            return in;
    }

    /**
    * @Description: 判断文件编码方式
    * @Author: zhangqian
    * @date 2019/4/26 4:18 PM
    */
    public static String guessEncoding(String filename) {
        try {
            if (logger.isDebugEnabled()) {
                logger.debug("filename" + filename);
            }

           /* CharsetPrinter charsetPrinter = new CharsetPrinter();
            String encode = charsetPrinter.guessEncoding(new File(filename));*/
           /* if (logger.isInfoEnabled()) {
                logger.info("encode:" + encode);
            }
            return encode;*/
        } catch (Exception var3) {
            throw new RuntimeException(var3);
        }
        return null;
    }

    /**
    * @Description: 方法说明
    * @Author: zhangqian
    * @date 2019/4/26 4:49 PM
    */
    public static String guessEncoding(File file) {
        try {
            /*CharsetPrinter charsetPrinter = new CharsetPrinter();
            String encode = charsetPrinter.guessEncoding(file);*/
            /*if (logger.isInfoEnabled()) {
                logger.info("encode:" + encode);
            }

            return encode;*/
        } catch (Exception var3) {
            throw new RuntimeException(var3);
        }
        return null;
    }
    /**
    * @Description: 用固定编码格式读取文件
    * @Author: zhangqian
    * @date 2019/4/26 4:19 PM
    */
    public static String readOther(File file, String encoding) {
        String string = "";
        BufferedReader in = null;
        try {
            in = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding));
            for(String str = ""; (str = in.readLine()) != null; string = string + str + "\n") {
                ;
            }

            in.close();
        } catch (Exception var13) {
            var13.printStackTrace();
        } finally {
            try {
                if (null != in) {
                    in.close();
                }
            } catch (IOException var12) {
                var12.printStackTrace();
            }

        }

        return string;
    }
    /**
     * @Description: 用固定编码格式读取文件
     * @Author: zhangqian
     * @date 2019/4/26 4:19 PM
     */
    public static String readUtf(File file, String encoding) {
        String string = "";
        BufferedReader in = null;
        FileInputStream fileInputStream = null;
        try {
            //  in = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding));
            fileInputStream = new FileInputStream(file);
            in = new BufferedReader(new UnicodeReader(fileInputStream, Charset.defaultCharset().name()));
            for(String str = ""; (str = in.readLine()) != null; string = string + str + "\n") {
                ;
            }

            in.close();
        } catch (Exception var13) {
            var13.printStackTrace();
        } finally {
            try {
                if (null != in) {
                    in.close();
                }
                if(null != fileInputStream){
                    fileInputStream.close();
                }
            } catch (IOException var12) {
                var12.printStackTrace();
            }

        }

        return string;
    }
    /**
    * @Description: 用固定编码格式写文件
    * @Author: zhangqian
    * @date 2019/4/26 4:20 PM
    */
    public static void write(File file, String encoding, String str) {
        if (logger.isInfoEnabled()) {
            logger.info("编码：" + encoding);
            logger.info("str:" + str);
        }

        BufferedWriter out = null;

        try {
            if (logger.isInfoEnabled()) {
                logger.info("开始读文件");
            }

            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), encoding));
            out.write(str);
            if (logger.isInfoEnabled()) {
                logger.info("读文件完毕");
            }

            out.close();
        } catch (Exception var13) {
            var13.printStackTrace();
        } finally {
            if (null != out) {
                try {
                    out.close();
                } catch (IOException var12) {
                    var12.printStackTrace();
                }
            }

        }

    }
}
